<template>
  <div class="attendance">
    <h3>运动员出勤</h3>
    <div class="attendance-top">
      <el-row type="flex" align="middle" justify="center">
        <el-col :span="1">
           运动项目
        </el-col>
        <el-col :span="6">
          <el-select v-model="sportId" @change="sportChange" filterable clearable
            placeholder="请选择">
            <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
          </el-select>
        </el-col>
        <el-col :span="1">
           日期
        </el-col>
        <el-col :span="5">
          <el-date-picker
            v-model="createDate"
            align="right"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-col>
        <el-col :span="5">
          <el-button-group>
            <el-button @click="dayPrevious" size="small" type="primary" icon="el-icon-arrow-left">上一天</el-button>
            <el-button @click="dayNext" size="small" type="primary">下一天<i class="el-icon-arrow-right el-icon--right"></i></el-button>
          </el-button-group>
        </el-col>
        <el-col :span="3" style="text-align: right;">
          <el-button type="primary" size="small" icon="el-icon-view" @click="dayAttendance">查看日出勤</el-button>
        </el-col>
      </el-row>
      <el-row type="flex" align="middle" justify="center" style="margin-top: 10px;">
        <el-col :span="1">
           教练员
        </el-col>
        <el-col :span="6">
          <el-select v-model="coachId" @change="coachChange" filterable clearable
            placeholder="请选择">
            <el-option :label="item.name" :value="item.coachId" v-for="(item,index) in coachData" :key="index"></el-option>
          </el-select>
        </el-col>
        <el-col :span="1">
           月份
        </el-col>
        <el-col :span="5">
          <el-date-picker
            v-model="month"
            align="right"
            type="month"
            placeholder="选择月份">
          </el-date-picker>
        </el-col>
        <el-col :span="5">
          <el-button-group>
            <el-button @click='monthPrevious' size="small" type="primary" icon="el-icon-arrow-left">上一月</el-button>
            <el-button @click='monthNext' size="small" type="primary">下一月<i class="el-icon-arrow-right el-icon--right"></i></el-button>
          </el-button-group>
        </el-col>
        <el-col :span="3" style="text-align: right;">
          <el-button type="primary" size="small" icon="el-icon-view" @click="monthAttendance">查看月出勤</el-button>
        </el-col>
      </el-row>
    </div>
    <el-card v-if="dayAttendanceShow" style="margin-top: 20px;">
      <vxe-toolbar>
        <template #buttons>
          <el-row type="flex">
            <el-col :span="11">
              <el-button type="success" icon="el-icon-plus" size="medium" @click="insterAttendance">新增</el-button>
              <el-button type="success" icon="el-icon-back" size="medium" @click="toYesterdayAttendance">从前一天导入</el-button>
              <el-button type="success" icon="el-icon-check" size="medium" @click="attendanceAll">全勤</el-button>
              <el-button type="success" icon="el-icon-refresh" size="medium" @click="resetAttendance">重置状态</el-button>
            </el-col>
            <el-col :span="8">
              <div v-show="addPlayerShow" size="medium" closable>
                <span>运动员</span>
                <el-select v-model="insertPlayerId" size="medium" filterable clearable placeholder="请选择" style="margin: 0 10px;">
                  <el-option :label="item" :value="key" v-for="(item,key,index) in insert_dict_player" :key="index"></el-option>
                </el-select>
                <el-button type="primary" size="medium" icon="el-icon-s-promotion" @click="insertPlayerSave">确认</el-button>
              </div>
            </el-col>
            <el-col :span="5">
              <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索" @input="searchEvent"></vxe-input>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>
      <vxe-table resizable ref="XTable" border max-height="800" stripe highlight-hover-row highlight-current-row :loading="loading" keep-source
        :data="playerAttendanceData" :edit-config="{trigger: 'click', mode: 'cell',showStatus: true,}" @edit-closed="editClosedEvent">
        <vxe-table-column field="player" title="运动员" width="100" sortable></vxe-table-column>
        <vxe-table-column field="createDate" title="创建时间" width="100" sortable></vxe-table-column>
        <vxe-table-column field="attendance" title="出勤情况" width="150" sortable :edit-render="{name: '$select', options: attendanceList}"></vxe-table-column>
        <vxe-table-column field="memo" title="备注" sortable :edit-render="{name: 'textarea'}"></vxe-table-column>
        <vxe-table-column field="" title="操作" width="50">
          <template #default="{ row }">
            <el-button @click="deleteEvent(row)" type="danger" size="medium" icon="el-icon-delete" circle></el-button>
          </template>
        </vxe-table-column>
      </vxe-table>
    </el-card>
    <el-card v-else style="margin-top: 20px;">
      <el-button type="success" icon="el-icon-printer" size="mini" @click="printEvent" style="margin-bottom: 20px;position: absolute;">打印</el-button>
      <div v-html="monthTable"></div>
    </el-card>
  </div>
</template>

<script>
  import {sport_by_org,ignoreRolePlayer,currentRolePlayer} from "@/api/dict.js"
  import {player_attendance_all,pcm4coach,player_attendance_update,player_attendance_delete,player_attendance_all_update,
  player_attendance_all_insert,month_player_attendance_all,update_player_pending} from "@/api/person.js"
  import {debounce} from '../../utils/common.js'
  export default {
    data() {
      return {
        attendanceList: [
          { label: '出勤',value: '出勤'},
          { label: '病假',value: '病假'},
          { label: '事假',value: '事假'},
          { label: '旷课',value: '旷课'},
          { label: '迟到',value: '迟到'},
          { label: '早退',value: '早退'},
        ],
        playerAttendanceData: [],
        defaultDataList: [],
        loading: false,
        dict_sport: {},
        dict_coache: {},
        dict_player: {},
        coachData: [],
        sportId: '',
        coachId: '',
        createDate: new Date(),
        month: new Date(),
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date());
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date);
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date);
            }
          }, {
            text: '一月前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 31);
              picker.$emit('pick', date);
            }
          }]
        },
        flowIdArr: [],
        filterName: '',
        searchProps: [],
        insert_dict_player: {},
        insertPlayerId: '',
        addPlayerShow: false,
        dayAttendanceShow: true,
        monthTable: '',
        title: '',
      }
    },
    created() {
      this.init_dict().then(()=>{
        this.getPlayerAttendance()
      })
    },
    methods: {
      resetAttendance() {
        update_player_pending({flowIds:this.flowIdArr.join(',')}).then(res=>{
          if(res.code === 200){
            this.getPlayerAttendance()
            this.$message.success('重置成功')
          }
        })
      },
      toYesterdayAttendance() {
        let createDate = this.$moment(this.createDate).add(-1, "d").format('YYYY-MM-DD')
        let flowArr = []
        this.getPlayerAttendance(createDate).then(res=>{
          this.defaultDataList.forEach((item,index)=>{
            flowArr.push(item.flowId)
          })
          this.defaultDataList = []
          this.flowIdArr = []
          res.forEach(item=>{
            let data = {
              playerId: item.playerId,
              createDate: this.$moment(this.createDate).format('YYYY-MM-DD')+' 00:00:00',
            }
            player_attendance_all_insert(data).then(res=>{
              if(res.code === 200) {
                res.data.player = this.dict_player[res.data.playerId]
                res.data.createDate = this.$moment(res.data.createDate).format('YYYY-MM-DD')
                res.data.attendance = '未记录'
                this.flowIdArr.push(res.data.flowId)
                this.defaultDataList.push(res.data)
                this.playerAttendanceData = this.defaultDataList
              }
            })
          })
          flowArr.forEach((item,index)=>{
            player_attendance_delete({flowId:item}).then(res=>{
              if(res.code === 200) {
                this.defaultDataList.forEach((item,index)=>{
                  if(item.flowId == res.data.flowId){
                    this.defaultDataList.splice(index,1)
                  }
                })
              }
            })
          })
        })
      },
      monthPrevious() {
        let currentDate = new Date(this.month)
        currentDate.setMonth(currentDate.getMonth() - 1)
        this.month = this.$moment(currentDate).format('YYYY-MM')
        this.monthAttendance()
      },
      monthNext() {
        let currentDate = new Date(this.month)
        currentDate.setMonth(currentDate.getMonth() + 1)
        this.month = this.$moment(currentDate).format('YYYY-MM')
        this.monthAttendance()
      },
      dayAttendance() {
        this.getPlayerAttendance()
        this.dayAttendanceShow = true
      },
      monthAttendance() {
        let date = this.$moment(this.month).format('YYYY-MM')
        let year = parseInt(date.split('-')[0]);
        let month = parseInt(date.split('-')[1]);
        let start = new Date(year, month - 1, 1);
        let end = new Date(year, month, 0);
        let openDate = this.$moment(start).format('YYYY-MM-DD')
        let closeDate = this.$moment(end).format('YYYY-MM-DD')
        let last = end.getDate()
        let data = {}
        data.openDate = openDate
        data.closeDate = closeDate
        if(this.coachId) data.coachId = this.coachId
        month_player_attendance_all(data).then(res=>{
          if(res.code === 200) {
            if(res.data.length != 0){
              this.monthTable = this.monthPlayerAttendanceTable(res.data,last,this.dict_player)
              this.dayAttendanceShow = false
            }else{
              this.$message.warning('没有记录,或检查是否选择教练员')
            }
          }else{
            this.$message.error(res.message)
          }
        })
      },
      monthPlayerAttendanceTable(data,last,dict_player) {
          let attendanceObj = {}
          data.forEach(item => {
              if (!attendanceObj[item.playerId]) {
                  attendanceObj[item.playerId] = {}
              }
              if(item.attendance == '未记录'){
                  item.attendance = ''
              }
              attendanceObj[item.playerId][this.$moment(item.createDate).date()] = item.attendance
          })
          let coachName = this.dict_coache[data[0].coachId]
          let sportName = this.dict_sport[this.sportId] || ''
          this.title = '运动员出勤表('+this.$moment(this.month).format('YYYY-MM')+'月)'
          let table = '<div style="width:100%;text-align:center;padding:10px 10px"><span style="font-size:120%">'+this.title+'</span><span style="float:right">'+sportName+' '+coachName+'</span></div>'
          table += '<table class="attendanceTable" border="1" style="border-collapse: collapse;" width="100%">'
          let tableHead = '<thead><tr>'
          tableHead += '<th class="thHead"><div class="date">日期</div><div class="name">姓名</div></th>'
          for (let i = 1; i <= last; i++) {
              tableHead += '<th>' + i + '</th>'
          }
          tableHead += '</tr></thead>'
          let tableBody = '<tbody>'
          for (let key in attendanceObj) {
              tableBody += '<tr style="height:30px"><td style="font-weight: bold">' + dict_player[key] + '</td>'
              let td = ''
              for (let i = 1; i <= last; i++) {
                  let attendanceDescr = attendanceObj[key][i]
                  if (attendanceDescr) {
                      td += "<td>" + attendanceDescr
                  } else {
                      td += "<td>"
                  }
              }
              tableBody += td + '</tr>'
          }
          table += tableHead
          table += tableBody
          table += '</table>'
          return table
      },
      printEvent() {
        let printStyle = `
          .attendanceTable thead tr th {
                      text-align: center;
            }

            .attendanceTable tbody tr td {
                height: 50px;
                width: 40px;
                text-align: center;
            }

            .attendanceTable .thHead {
                width: 50px;
                height: 50px;
                /*margin-left:50px;*/
                box-sizing: border-box;
                border: 1px solid #444343;
                background: linear-gradient(39deg, transparent 49.5%, #444343 49.5%, #444343 50.5%, transparent 50.5%);
            }

            .attendanceTable .thHead .name {
                text-align: left;
            }

            .attendanceTable .thHead .date {
                text-align: right;
            }
        `
        document.title = this.title
        this.$XPrint({
          sheetName: this.title,
          style: printStyle,
          content: this.monthTable,
        })
      },
      attendanceAll() {
        player_attendance_all_update({flowIds:this.flowIdArr.join(',')}).then(res=>{
          if(res.code === 200) {
            this.$message.success('全勤，修改成功！')
            this.getPlayerAttendance()
          }
        })
      },
      insertPlayerSave() {
        let data = {
          playerId:this.insertPlayerId,
          createDate:this.$moment(this.createDate).format('YYYY-MM-DD')+' 00:00:00',
        }
        player_attendance_all_insert(data).then(res=>{
          if(res.code === 200) {
            this.getPlayerAttendance()
            this.$message.success(this.dict_player[this.insertPlayerId]+'添加成功！')
            delete this.insert_dict_player[this.insertPlayerId]
            this.insertPlayerId = ''
            this.insertPlayerId = Object.keys(this.insert_dict_player)[0]
          }else{
            this.$message.error(res.message)
          }
        })
      },
      insterAttendance() {
        currentRolePlayer().then(res=>{
          this.insert_dict_player = res
          this.defaultDataList.forEach(item=>{
            delete this.insert_dict_player[item.playerId]
          })
          this.insertPlayerId = Object.keys(this.insert_dict_player)[0]
          this.addPlayerShow = true
        })
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.playerAttendanceData = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
        } else {
          this.playerAttendanceData = this.defaultDataList
        }
      },
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          player_attendance_delete({flowId:row.flowId}).then(res=>{
            if(res.code === 200) {
              this.$message.success('删除成功！')
              this.defaultDataList.forEach((item,index)=>{
                if(item.flowId == row.flowId){
                  this.defaultDataList.splice(index,1)
                }
              })
              this.playerAttendanceData = this.defaultDataList
              let obj = {}
              obj[row.playerId] = row.player
              Object.assign(this.insert_dict_player,obj)
              this.insertPlayerId = row.playerId
            }else{
              this.$message.error(res.message)
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      editClosedEvent({ row, column }) {
        const $table = this.$refs.XTable
        const field = column.property
        const cellValue = row[field]
        let data = {}
        data.flowId = row.flowId
        data[field] = row[field]
        if ($table.isUpdateByRow(row, field)) {
          player_attendance_update(data).then(res=>{
            if(res.code === 200) {
              $table.reloadRow(row, null, field)
              this.$message.success('保存成功！')
            }else{
              this.$message.error(res.message)
            }
          })
        }
      },
      dayPrevious() {
        let currentDate = new Date(this.createDate)
        currentDate.setDate(currentDate.getDate() - 1)
        this.createDate = this.$moment(currentDate).format('YYYY-MM-DD')
        this.getPlayerAttendance().then(()=>{
          this.insterAttendance()
        })
      },
      dayNext() {
        let currentDate = new Date(this.createDate)
        currentDate.setDate(currentDate.getDate() + 1)
        this.createDate = this.$moment(currentDate).format('YYYY-MM-DD')
        this.getPlayerAttendance().then(()=>{
          console.log(111)
          this.insterAttendance()
        })
      },
      coachChange(val) {
        this.getPlayerAttendance()
      },
      sportChange(val) {
        this.coachId = ''
        pcm4coach({sportId:val}).then(res=>{
          if(res.code === 200) {
            res.data.forEach(item=>{
              this.dict_coache[item.coachId] = item.name
            })
            this.coachData = res.data
          }
        })
      },
      getPlayerAttendance(yesterday) {
        return new Promise((resolve,reject)=>{
          let data = {}
          this.flowIdArr = []
          this.loading = true
          if(yesterday){
            data.createDate = this.$moment(yesterday).format('YYYY-MM-DD')
          }else{
            if(this.createDate) data.createDate = this.$moment(this.createDate).format('YYYY-MM-DD')
          }
          if(this.coachId) data.coachId = this.coachId
          player_attendance_all(data).then(res=>{
            if(res.code === 200) {
              if(res.data.length != 0){
                if(yesterday){
                  resolve(res.data)
                }else{
                  res.data.forEach(item=>{
                    item.player = this.dict_player[item.playerId]
                    item.createDate = this.$moment(item.createDate).format('YYYY-MM-DD')
                    this.flowIdArr.push(item.flowId)
                  })
                  this.searchProps = Object.keys(res.data[0])
                  this.defaultDataList = res.data
                  this.playerAttendanceData = res.data
                  resolve()
                }
              }
            }
            this.dayAttendanceShow = true
            this.loading = false
          })
        })
      },
      init_dict() {
        return new Promise((resolve,reject)=>{
          sport_by_org().then(res=>{
            this.dict_sport = res
          })
          pcm4coach().then(res=>{
            if(res.code === 200) {
              res.data.forEach(item=>{
                this.dict_coache[item.coachId] = item.name
              })
            }
          })
          ignoreRolePlayer().then(res=>{
            this.dict_player = res
            resolve()
          })
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .attendance{
    .attendance-top{
      background-color: #FFFFFF;
      padding: 20px;
      border-bottom-left-radius: 4px;
      border-bottom-right-radius: 4px;
    }
  }
</style>
